package com.glodon.paas.framework.registry.client.web;

import com.glodon.paas.framework.registry.client.status.ClientStatusManager;
import com.glodon.paas.framework.registry.core.status.ClientStatus;
import org.apache.zookeeper.ZooKeeper;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;

/**
 * SRDS client status listener, which handle client status changes
 *
 * @author Don Li
 */
public class ClientStatusListener implements ServletContextAttributeListener {

    private ClientStatusManager manager = new ClientStatusManager();

    public ClientStatusListener() {
    }

    @Override
    public void attributeAdded(ServletContextAttributeEvent scab) {
        process(scab);
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent scab) {
        // nothing to do here
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent scab) {
        process(scab);
    }

    private void process(ServletContextAttributeEvent scab) {
        if (scab.getName().equals(ClientBootstrapListener.CLIENT_ZOOKEEPER)) {
            manager.setZk((ZooKeeper) scab.getValue());
        } else if (scab.getName().equals(ClientBootstrapListener.CLIENT_PATH)) {
            manager.setPath((String) scab.getValue());
        } else if (scab.getName().equals(ClientBootstrapListener.CLIENT_STATUS)) {
            manager.setClientStatus((ClientStatus) scab.getValue());
        }
    }


}
